﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.Core.MFG.EntityHelper;
using Kingdee.K3.Core.MFG.Utils;
using Kingdee.K3.MFG.ServiceHelper.PRD;

namespace DzInfo.FormPlugIn.ND
{
    [Description("纳德扩展：生产用料清单应发数量修改插件")]

    public class PPBOMMQModifyExt : AbstractDynamicFormPlugIn
    {
        private bool isReValue;

        private List<long> ppbomIds { get; set; }

        private List<long> ppbomEntryIds { get; set; }

        private Dictionary<long, List<long>> dicPPBOMIdS { get; set; }

        private decimal useRateRange { get; set; }

        private Dictionary<long, IGrouping<long, DynamicObject>> dicppbomDatas { get; set; }

        private string formId { get; set; }

        private List<long> ppbomCHEntryIds { get; set; }

        private Dictionary<long, IGrouping<long, DynamicObject>> dicppbomChangeDatas { get; set; }

        public override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            dicPPBOMIdS = View.OpenParameter.GetCustomParameter("DICPPBOMIDS") as Dictionary<long, List<long>>;
            ppbomIds = View.OpenParameter.GetCustomParameter("PPBOMIDS") as List<long>;
            ppbomEntryIds = View.OpenParameter.GetCustomParameter("PPBOMENTRYIDS") as List<long>;
            useRateRange = Convert.ToDecimal(View.OpenParameter.GetCustomParameter("UseRateRange"));
            List<DynamicObject> list = View.OpenParameter.GetCustomParameter("ppbomDatas") as List<DynamicObject>;
            dicppbomDatas = (from g in list
                             group g by g.GetDynamicValue("Id", 0L)).ToDictionary((IGrouping<long, DynamicObject> d) => d.Key);
            formId = Convert.ToString(View.OpenParameter.GetCustomParameter("FORMID"));
            ppbomCHEntryIds = View.OpenParameter.GetCustomParameter("PPBOMCHENTRYIDS") as List<long>;
            FillPPBOMDatas();
            if (formId == "PRD_PPBOM")
            {
                SetComReplace();
            }
            else
            {
                if (!(formId == "PRD_PPBOMChange"))
                {
                    return;
                }
                List<DynamicObject> list2 = new List<DynamicObject>();
                foreach (DynamicObject item in list)
                {
                    DynamicObjectCollection dynamicValue = item.GetDynamicValue<DynamicObjectCollection>("PPBomEntry");
                    if (!dynamicValue.IsEmpty())
                    {
                        list2.AddRange(dynamicValue);
                    }
                }
                if (!list2.IsEmpty())
                {
                    dicppbomChangeDatas = (from g in list2
                                           group g by g.GetDynamicValue("PPBOMId", 0L)).ToDictionary((IGrouping<long, DynamicObject> d) => d.Key);
                    SetComReplaceForChange();
                }
            }
        }

        public override void BeforeUpdateValue(BeforeUpdateValueEventArgs e)
        {
            base.BeforeUpdateValue(e);
            string text;
            if ((text = e.Key.ToUpperInvariant()) != null && text == "FMUSTQTY")
            {
                bool value = View.Model.GetValue("FIsGetScrap", e.Row, defValue: false, "FEntity");
                decimal value2 = View.Model.GetValue("FFixScrapQty", e.Row, 0m, "FEntity");
                if (value && Convert.ToDecimal(e.Value) < value2)
                {
                    View.ShowErrMessage(string.Format(ResManager.LoadKDString("第{0}行分录，当发损耗时应发数量不能小于固定损耗", "015078000038986", SubSystemType.MFG), e.Row + 1));
                    e.Cancel = true;
                }
            }
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            switch (e.Field.Key)
            {
                case "F_BlQty":
                    decimal blQty = (decimal)e.NewValue;
                    Entity entity2 = View.BusinessInfo.GetEntity("FEntity");
                    var rowData2 = this.Model.GetEntityDataObject(entity2, e.Row);
                    decimal ycQty = Convert.ToDecimal(rowData2["F_YCQty"]);
                    decimal yfQty = blQty / 100m * ycQty;
                    this.Model.SetValue("FMustQty", yfQty, e.Row);
                    break;
                case "FMustQty":
                    MustQtyChange(e.Row);
                    Entity entity1 = View.BusinessInfo.GetEntity("FEntity");
                    var rowData = this.Model.GetEntityDataObject(entity1, e.Row);
                    decimal oldQty = Convert.ToDecimal(rowData["F_YCQty"]);
                    decimal newQty = (decimal)e.NewValue;
                    this.Model.SetValue("F_TZQty", oldQty - newQty, e.Row);
                    break;
                case "FUseRate":
                    UseRateChanged(e.Row);
                    break;
                case "FIsSelect":
                    {
                        if (isReValue)
                        {
                            break;
                        }
                        Entity entity = View.BusinessInfo.GetEntity("FEntity");
                        DynamicObjectCollection entityDataObject = View.Model.GetEntityDataObject(entity);
                        Dictionary<string, IGrouping<string, DynamicObject>> dictionary = (from g in entityDataObject
                                                                                           group g by g.GetDynamicValue("PrdPPBomId", 0L) + "_" + g.GetDynamicValue<string>("ReplaceGroup")).ToDictionary((IGrouping<string, DynamicObject> d) => d.Key);
                        int value = View.Model.GetValue("FReplaceGroup", e.Row, 0, "FEntity");
                        long value2 = View.Model.GetValue("FPrdPPBomId", e.Row, 0L, "FEntity");
                        string key = value2 + "_" + value;
                        dictionary.TryGetValue(key, out var value3);
                        if (value3.Count() <= 1)
                        {
                            break;
                        }
                        isReValue = true;
                        foreach (DynamicObject item in value3)
                        {
                            int dynamicValue = item.GetDynamicValue("Seq", 0);
                            View.Model.SetValue("FIsSelect", e.NewValue, dynamicValue - 1);
                        }
                        isReValue = false;
                        break;
                    }
            }
        }

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            switch (e.BarItemKey)
            {
                case "tbReturnData":
                    WriteBackPPBOM(e);
                    break;
                case "tbDelEntryRow":
                    DeleteEntryRow();
                    break;
                case "tbExpandAllRows":
                    {
                        TreeEntryGrid control = View.GetControl<TreeEntryGrid>("FEntity");
                        Entity entity = View.BusinessInfo.GetEntity("FEntity");
                        DynamicObjectCollection ppBomEntrys = View.Model.GetEntityDataObject(entity);
                        if (ppBomEntrys.IsEmpty())
                        {
                            break;
                        }
                        List<string> list = (from t in ppBomEntrys
                                             where "3".Equals(t["MaterialType"].ConvertTo<string>())
                                             select t into x
                                             select x["ParentRowId"].ConvertTo<string>()).ToList();
                        Dictionary<string, int> dictionary = ppBomEntrys.ToDictionary((DynamicObject x) => x["SROWID"].ConvertTo<string>(), (DynamicObject y) => ppBomEntrys.IndexOf(y));
                        if (list.IsEmpty())
                        {
                            break;
                        }
                        int value = 0;
                        {
                            foreach (string item in list)
                            {
                                if (dictionary.TryGetValue(item, out value))
                                {
                                    control.ExpandedRow(value);
                                }
                            }
                            break;
                        }
                    }
            }
        }

        private void FillPPBOMDatas()
        {
            Entity entity = View.BusinessInfo.GetEntity("FEntity");
            DynamicObjectCollection entityDataObject = View.Model.GetEntityDataObject(entity);
            entityDataObject.Clear();
            List<DynamicObject> list = new List<DynamicObject>();
            list = ((!(formId == "PRD_PPBOM")) ? PPBOMServiceHelper.GetPPBOMCHEntryDatas(base.Context, ppbomCHEntryIds).ToList() : PPBOMServiceHelper.GetPPBOMEntryDatas(base.Context, dicPPBOMIdS, ppbomIds, ppbomEntryIds).ToList());
            if (list.IsEmpty())
            {
                View.ShowMessage(ResManager.LoadKDString("生产用料清单选中行子项类型是返还件或分录属于组合替代的被替代料或替代料", "015078000038987", SubSystemType.MFG));
                return;
            }
            Model.BeginIniti();
            foreach (DynamicObject item in list)
            {
                var MustQty = item["MustQty"];
                item["F_YCQty"] = MustQty;
                entityDataObject.Add(item);
            }
            Model.EndIniti();
            View.UpdateView("FEntity");
        }

        private void SetComReplace()
        {
            DynamicObjectCollection dynamicValue = View.Model.DataObject.GetDynamicValue<DynamicObjectCollection>("Entity");
            List<long> list = new List<long>();
            foreach (DynamicObject item in dynamicValue)
            {
                long ppbomEntryId = item.GetDynamicValue("PPBOMEntryId", 0L);
                if (list.Contains(ppbomEntryId))
                {
                    continue;
                }
                long dynamicValue2 = item.GetDynamicValue("PPBOMID", 0L);
                int replaceGroup = item.GetDynamicValue("ReplaceGroup", 0);
                string dynamicValue3 = item.GetDynamicValue<string>("MaterialType");
                if (dynamicValue3 != "3" || !dicppbomDatas.TryGetValue(dynamicValue2, out var value))
                {
                    continue;
                }
                DynamicObjectCollection dynamicValue4 = value.FirstOrDefault().GetDynamicValue<DynamicObjectCollection>("PPBomEntry");
                DynamicObject dynamicObject = dynamicValue4.Where((DynamicObject w) => w.GetDynamicValue("Id", 0L) == ppbomEntryId).FirstOrDefault();
                int replacePriority = dynamicObject.GetDynamicValue("ReplacePriority", 0);
                if (!dynamicObject.GetDynamicValue("IsKeyItem", defValue: false))
                {
                    continue;
                }
                List<DynamicObject> list2 = dynamicValue4.Where((DynamicObject w) => w.GetDynamicValue("ReplaceGroup", 0) == replaceGroup && w.GetDynamicValue("ReplacePriority", 0) == replacePriority && w.GetDynamicValue("Id", 0L) != ppbomEntryId).ToList();
                if (list2.IsEmpty())
                {
                    continue;
                }
                List<long> list3 = list2.Select((DynamicObject s) => s.GetDynamicValue("Id", 0L)).ToList();
                list.AddRange(list3);
                string value2 = SequentialGuid.NewGuid().ToString();
                int row = dynamicValue.IndexOf(item);
                View.Model.SetValue("FGroup", value2, row);
                foreach (long entryId in list3)
                {
                    Func<DynamicObject, bool> predicate = (DynamicObject w) => w.GetDynamicValue("PPBOMEntryId", 0L) == entryId;
                    row = dynamicValue.IndexOf(dynamicValue.Where(predicate).FirstOrDefault());
                    View.Model.SetValue("FGroup", value2, row);
                    View.Model.SetValue("FIsLock", true, row);
                }
            }
        }

        private void SetComReplaceForChange()
        {
            DynamicObjectCollection dynamicValue = View.Model.DataObject.GetDynamicValue<DynamicObjectCollection>("Entity");
            List<long> list = new List<long>();
            foreach (DynamicObject item in dynamicValue)
            {
                long ppbomEntryId = item.GetDynamicValue("PPBOMEntryId", 0L);
                if (list.Contains(ppbomEntryId))
                {
                    continue;
                }
                long dynamicValue2 = item.GetDynamicValue("PrdPPBomId", 0L);
                int replaceGroup = item.GetDynamicValue("ReplaceGroup", 0);
                string dynamicValue3 = item.GetDynamicValue<string>("MaterialType");
                if (dynamicValue3 != "3" || !dicppbomChangeDatas.TryGetValue(dynamicValue2, out var value))
                {
                    continue;
                }
                IEnumerable<DynamicObject> enumerable = value.Where((DynamicObject w) => w.GetDynamicValue("Id", 0L) == ppbomEntryId);
                if (enumerable.IsEmpty())
                {
                    continue;
                }
                DynamicObject dynamicObject = enumerable.FirstOrDefault();
                int replacePriority = dynamicObject.GetDynamicValue("ReplacePriority", 0);
                if (!dynamicObject.GetDynamicValue("IsKeyItem", defValue: false))
                {
                    continue;
                }
                List<DynamicObject> list2 = value.Where((DynamicObject w) => w.GetDynamicValue("ReplaceGroup", 0) == replaceGroup && w.GetDynamicValue("ReplacePriority", 0) == replacePriority && w.GetDynamicValue("Id", 0L) != ppbomEntryId).ToList();
                if (list2.IsEmpty())
                {
                    continue;
                }
                List<long> list3 = list2.Select((DynamicObject s) => s.GetDynamicValue("Id", 0L)).ToList();
                list.AddRange(list3);
                string value2 = Guid.NewGuid().ToString();
                int row = dynamicValue.IndexOf(item);
                View.Model.SetValue("FGroup", value2, row);
                foreach (long entryId in list3)
                {
                    Func<DynamicObject, bool> predicate = (DynamicObject w) => w.GetDynamicValue("PPBOMEntryId", 0L) == entryId;
                    row = dynamicValue.IndexOf(dynamicValue.Where(predicate).FirstOrDefault());
                    View.Model.SetValue("FGroup", value2, row);
                    View.Model.SetValue("FIsLock", true, row);
                }
            }
        }

        private void MustQtyChange(int row)
        {
            if (View.Model.GetValue("FIsLock", row, defValue: true, "FEntity"))
            {
                return;
            }
            Entity entity = View.BusinessInfo.GetEntity("FEntity");
            DynamicObjectCollection entityDataObject = View.Model.GetEntityDataObject(entity);
            decimal value = View.Model.GetValue("FMustQty", row, 0m, "FEntity");
            int value2 = View.Model.GetValue("FReplaceGroup", row, 0, "FEntity");
            long value3 = View.Model.GetValue("FPPBOMID", row, 0L, "FEntity");
            dicppbomDatas.TryGetValue(value3, out var value4);
            long ppbomEntryId = View.Model.GetValue("FPPBOMEntryId", row, 0L, "FEntity");
            DynamicObjectCollection dynamicValue = value4.FirstOrDefault().GetDynamicValue<DynamicObjectCollection>("PPBomEntry");
            DynamicObject dynamicObject = dynamicValue.Where((DynamicObject w) => w.GetDynamicValue("Id", 0L) == ppbomEntryId).FirstOrDefault();
            int row2 = dynamicValue.IndexOf(dynamicObject);
            string value5 = View.Model.GetValue("FDosageType", row, "2", "FEntity");
            bool value6 = View.Model.GetValue("FIsGetScrap", row, defValue: false, "FEntity");
            decimal value7 = View.Model.GetValue("FFixScrapQty", row, 0m, "FEntity");
            decimal value8 = View.Model.GetValue("FScrapRate", row, 0m, "FEntity");
            value8 /= 100m;
            decimal value9 = View.Model.GetValue("FQty", row, 0m, "FEntity");
            decimal value10 = View.Model.GetValue("FUseRate", row, 0m, "FEntity");
            value10 /= 100m;
            decimal value11 = View.Model.GetValue("FNumerator", row, 0m, "FEntity");
            decimal value12 = View.Model.GetValue("FDenominator", row, 0m, "FEntity");
            long value13 = View.Model.GetValue("FPrdPPBomId", row, 0L, "FEntity");
            string key = value13 + "_" + value2;
            if (IsReplace(key, entityDataObject))
            {
                value10 = ((value5 != "1" && value6) ? ((value - value7) / (value9 * (value8 + 1m) * value11 / value12)) : ((value5 != "1" && !value6) ? (value / (value9 * value11 / value12)) : ((!(value5 == "1") || !value6) ? (value * value12 / value11) : ((value - value7) * value12 / (value11 * (value8 + 1m))))));
                View.Model.SetValue("FUseRate", value10 * 100m, row);
                SetComReplaceMustQty(row, entityDataObject, value10 * 100m);
            }
            else
            {
                if (value5 != "1" && value6)
                {
                    value11 = value - value7;
                    value12 = value9 * value10 * (value8 + 1m);
                }
                else if (value5 != "1" && !value6)
                {
                    value11 = value;
                    value12 = value9;
                }
                else if (value5 == "1" && value6)
                {
                    value11 = (value - value7) / (value10 * (value8 + 1m));
                    value12 = 1m;
                }
                else
                {
                    value11 = value;
                    value12 = 1m;
                }
                int num = 0;
                int num2 = Convert.ToInt32(value11);
                num = Convert.ToInt32(value12);
                if ((decimal)num2 == value11 && (decimal)num == value12)
                {
                    PRDCommonServiceHelper.GetPureDecimalGcb(base.Context, value11, value12, out value11, out value12);
                }
                View.Model.SetValue("FNumerator", value11, row);
                View.Model.SetValue("FDenominator", value12, row);
            }
            if (value6)
            {
                View.Model.SetValue("FNeedQty", value, row);
                decimal num3 = (value - value7) / (value8 + 1m);
                View.Model.SetValue("FStdQty", num3, row);
                dynamicObject.SetDynamicObjectItemValue("StdQty", num3);
            }
            else
            {
                View.Model.SetValue("FStdQty", value, row);
                dynamicObject.SetDynamicObjectItemValue("StdQty", value);
                decimal num4 = value * (value8 + 1m) + value7;
                View.Model.SetValue("FNeedQty", num4, row);
            }
            decimal num5 = PPBOMCalQtyServiceHelper.CalConsumeQty(base.Context, value4.FirstOrDefault(), row2);
            View.Model.SetValue("FConsumeQty", num5, row);
            dynamicObject.SetDynamicObjectItemValue("ConsumeQty", num5);
            decimal num6 = PPBOMCalQtyServiceHelper.CalWipQty(base.Context, value4.FirstOrDefault(), row2);
            View.Model.SetValue("FWipQty", num6, row);
        }

        private bool IsReplace(string key, DynamicObjectCollection entryDatas)
        {
            Dictionary<string, IGrouping<string, DynamicObject>> dictionary = (from g in entryDatas
                                                                               group g by g.GetDynamicValue("PrdPPBomId", 0L) + "_" + g.GetDynamicValue("ReplaceGroup", 0)).ToDictionary((IGrouping<string, DynamicObject> d) => d.Key);
            dictionary.TryGetValue(key, out var value);
            if (value.Count() > 1)
            {
                return true;
            }
            return false;
        }

        private void WriteBackPPBOM(BarItemClickEventArgs e)
        {
            Entity entity = View.BusinessInfo.GetEntity("FEntity");
            List<DynamicObject> list = (from w in View.Model.GetEntityDataObject(entity)
                                        where w.GetDynamicValue("IsSelect", defValue: false)
                                        select w).ToList();
            if (list.IsEmpty())
            {
                return;
            }
            Dictionary<string, IGrouping<string, DynamicObject>> dictionary = (from g in list
                                                                               group g by g.GetDynamicValue("PrdPPBomId", 0L) + "_" + g.GetDynamicValue<string>("ReplaceGroup")).ToDictionary((IGrouping<string, DynamicObject> d) => d.Key);
            string text = string.Empty;
            Dictionary<long, decimal> dictionary2 = new Dictionary<long, decimal>();
            int num = 1;
            foreach (KeyValuePair<string, IGrouping<string, DynamicObject>> item3 in dictionary)
            {
                if (item3.Value.Count() == 1)
                {
                    continue;
                }
                List<DynamicObject> list2 = item3.Value.Where((DynamicObject w) => !w.GetDynamicValue("IsLock", defValue: false)).ToList();
                decimal num2 = list2.Sum((DynamicObject s) => s.GetDynamicValue("UseRate", 0m));
                if (num2 > 100m + useRateRange || num2 < 100m - useRateRange)
                {
                    string text2 = string.Empty;
                    foreach (DynamicObject item4 in list2)
                    {
                        int dynamicValue = item4.GetDynamicValue("Seq", 0);
                        text2 = text2 + dynamicValue + ",";
                    }
                    object obj = text;
                    text = string.Concat(obj, "\n", num, "、", string.Format(ResManager.LoadKDString("第{0}行使用比例之和不在{1}~{2}范围内,请检查", "015078000038988", SubSystemType.MFG), text2.TrimEnd(','), 100m - useRateRange, 100m + useRateRange));
                }
                else if (num2 <= 100m + useRateRange && num2 >= 100m - useRateRange && num2 != 100m)
                {
                    int maxSeq = list2.Where((DynamicObject w) => w.GetDynamicValue("MustQty", 0m) > 0m).Max((DynamicObject m) => m.GetDynamicValue("Seq", 0));
                    decimal num3 = list2.Where((DynamicObject w) => w.GetDynamicValue("Seq", 0) != maxSeq).Sum((DynamicObject s) => s.GetDynamicValue("UseRate", 0m));
                    long dynamicValue2 = list2.Where((DynamicObject w) => w.GetDynamicValue("Seq", 0) == maxSeq).FirstOrDefault().GetDynamicValue("PPBOMEntryId", 0L);
                    dictionary2.Add(dynamicValue2, (num3 < 100m) ? (100m - num3) : (num3 - 100m));
                }
            }
            List<IGrouping<int, DynamicObject>> list3 = (from w in list
                                                         where w.GetDynamicObjectItemValue<string>("ReplacePolicy") == "2"
                                                         select w into o
                                                         group o by o.GetDynamicObjectItemValue("ReplaceGroup", 0)).ToList();
            foreach (IGrouping<int, DynamicObject> item5 in list3)
            {
                List<string> list4 = new List<string>();
                IEnumerable<DynamicObject> enumerable = item5.Where((DynamicObject w) => w.GetDynamicObjectItemValue("UseRate", 0m) != 100m && w.GetDynamicObjectItemValue("UseRate", 0m) != 0m);
                if (enumerable != null && enumerable.Count() > 0)
                {
                    string item = string.Join(",", item5.Select((DynamicObject t) => t.GetDynamicObjectItemValue("Seq", 0)));
                    list4.Add(item);
                }
                if (!list4.IsEmpty())
                {
                    text = text + "\n" + string.Format(ResManager.LoadKDString("第{0}行整批替代中只能是主料或替代料的任一替代主料使用比例为100%，请修正！", "015078000037717", SubSystemType.MFG), string.Join("],[", list4));
                }
            }
            if (text.Length > 0)
            {
                View.ShowErrMessage(text);
                e.Cancel = true;
                return;
            }
            foreach (KeyValuePair<long, decimal> item2 in dictionary2)
            {
                Func<DynamicObject, bool> predicate = delegate (DynamicObject w)
                {
                    long dynamicValue3 = w.GetDynamicValue("PPBOMEntryId", 0L);
                    KeyValuePair<long, decimal> keyValuePair = item2;
                    return dynamicValue3 == keyValuePair.Key;
                };
                DynamicObject dynamicObject = list.Where(predicate).FirstOrDefault();
                string groupId = dynamicObject.GetDynamicValue<string>("Group");
                List<DynamicObject> list5 = new List<DynamicObject>();
                list5.Add(dynamicObject);
                if (!groupId.IsNullOrEmptyOrWhiteSpace())
                {
                    List<DynamicObject> collection = list.Where((DynamicObject w) => w.GetDynamicValue<string>("Group") == groupId && w.GetDynamicValue("IsLock", defValue: false)).ToList();
                    list5.AddRange(collection);
                }
                foreach (DynamicObject item6 in list5)
                {
                    long ppbomEntryId = item6.GetDynamicValue("PPBOMEntryId", 0L);
                    DynamicObject dynamicObject2 = list.Where((DynamicObject w) => w.GetDynamicValue("PPBOMEntryId", 0L) == ppbomEntryId).FirstOrDefault();
                    KeyValuePair<long, decimal> keyValuePair2 = item2;
                    dynamicObject2.SetDynamicObjectItemValue("UseRate", keyValuePair2.Value);
                    KeyValuePair<long, decimal> keyValuePair3 = item2;
                    if (keyValuePair3.Value == 0m)
                    {
                        dynamicObject2.SetDynamicObjectItemValue("MustQty", 0);
                        dynamicObject2.SetDynamicObjectItemValue("BaseMustQty", 0);
                        dynamicObject2.SetDynamicObjectItemValue("NeedQty", 0);
                        dynamicObject2.SetDynamicObjectItemValue("BaseNeedQty", 0);
                        dynamicObject2.SetDynamicObjectItemValue("StdQty", 0);
                        dynamicObject2.SetDynamicObjectItemValue("BaseStdQty", 0);
                    }
                }
            }
            SaveTargetDatas(list);
        }

        private void WriteBackPPBOMCH()
        {
            Entity entity = View.BusinessInfo.GetEntity("FEntity");
            List<DynamicObject> list = (from w in View.Model.GetEntityDataObject(entity)
                                        where w.GetDynamicValue("IsSelect", defValue: false)
                                        select w).ToList();
            if (!list.IsEmpty())
            {
                SaveTargetDatas(list);
            }
        }

        private void SaveTargetDatas(List<DynamicObject> entrys)
        {
            List<DynamicObject> list = new List<DynamicObject>();
            foreach (DynamicObject entry in entrys)
            {
                long dynamicValue = entry.GetDynamicValue("PPBOMID", 0L);
                long ppbomEntryId = entry.GetDynamicValue("PPBOMEntryId", 0L);
                dicppbomDatas.TryGetValue(dynamicValue, out var value);
                if (value.IsEmpty())
                {
                    continue;
                }
                DynamicObjectCollection dynamicValue2 = value.FirstOrDefault().GetDynamicValue<DynamicObjectCollection>("PPBomEntry");
                List<DynamicObject> list2 = dynamicValue2.Where((DynamicObject w) => w.GetDynamicValue("Id", 0L) == ppbomEntryId).ToList();
                if (!list2.IsEmpty())
                {
                    decimal tzQty = entry.GetDynamicValue("F_TZQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("F_TZQty", tzQty);

                    decimal dynamicValue3 = entry.GetDynamicValue("UseRate", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("UseRate", dynamicValue3);
                    decimal dynamicValue4 = entry.GetDynamicValue("Numerator", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("Numerator", dynamicValue4);
                    decimal dynamicValue5 = entry.GetDynamicValue("BaseNumerator", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseNumerator", dynamicValue5);
                    decimal dynamicValue6 = entry.GetDynamicValue("Denominator", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("Denominator", dynamicValue6);
                    decimal dynamicValue7 = entry.GetDynamicValue("BASEDENOMINATOR", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseDenominator", dynamicValue7);
                    decimal dynamicValue8 = entry.GetDynamicValue("MustQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("MustQty", dynamicValue8);
                    decimal dynamicValue9 = entry.GetDynamicValue("BaseMustQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseMustQty", dynamicValue9);
                    decimal dynamicValue10 = entry.GetDynamicValue("StdQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("StdQty", dynamicValue10);
                    decimal dynamicValue11 = entry.GetDynamicValue("BaseStdQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseStdQty", dynamicValue11);
                    decimal dynamicValue12 = entry.GetDynamicValue("NeedQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("NeedQty", dynamicValue12);
                    decimal dynamicValue13 = entry.GetDynamicValue("BaseNeedQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseNeedQty", dynamicValue13);
                    decimal dynamicValue14 = entry.GetDynamicValue("ConsumeQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("ConsumeQty", dynamicValue14);
                    decimal dynamicValue15 = entry.GetDynamicValue("BaseConsumeQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseConsumeQty", dynamicValue15);
                    decimal dynamicValue16 = entry.GetDynamicValue("WipQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("WipQty", dynamicValue16);
                    decimal dynamicValue17 = entry.GetDynamicValue("BaseWipQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseWipQty", dynamicValue17);
                    decimal dynamicValue18 = list2.FirstOrDefault().GetDynamicValue("MustQty", 0m);
                    decimal dynamicValue19 = list2.FirstOrDefault().GetDynamicValue("BaseMustQty", 0m);
                    decimal dynamicValue20 = list2.FirstOrDefault().GetDynamicValue("PickedQty", 0m);
                    decimal dynamicValue21 = list2.FirstOrDefault().GetDynamicValue("BasePickedQty", 0m);
                    decimal dynamicValue22 = list2.FirstOrDefault().GetDynamicValue("GoodReturnQty", 0m);
                    decimal dynamicValue23 = list2.FirstOrDefault().GetDynamicValue("BaseGoodReturnQty", 0m);
                    decimal dynamicValue24 = list2.FirstOrDefault().GetDynamicValue("INCDefectReturnQty", 0m);
                    decimal dynamicValue25 = list2.FirstOrDefault().GetDynamicValue("BaseIncDefectReturnQty", 0m);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("NoPickedQty", dynamicValue18 - dynamicValue20 + dynamicValue22 + dynamicValue24);
                    list2.FirstOrDefault().SetDynamicObjectItemValue("BaseNoPickedQty", dynamicValue19 - dynamicValue21 + dynamicValue23 + dynamicValue25);
                    if (formId == "PRD_PPBOM")
                    {
                        list2.FirstOrDefault().SetDynamicObjectItemValue("ISMODIFYMQ", true);
                    }
                    if (!list.Contains(value.FirstOrDefault()))
                    {
                        list.Add(value.FirstOrDefault());
                    }
                }
            }
            FormMetadata formMetadata = (FormMetadata)MetaDataServiceHelper.Load(base.Context, formId);
            IOperationResult param = BusinessDataServiceHelper.Save(base.Context, formMetadata.BusinessInfo, list.ToArray(), OperateOption.Create(), "Save");
            View.ReturnToParentWindow(param);
            View.Close();
        }

        private void DeleteEntryRow()
        {
            EntryEntity entryEntity = View.BusinessInfo.GetEntryEntity("FEntity");
            int[] selectedRows = View.GetControl<EntryGrid>("FEntity").GetSelectedRows();
            if (selectedRows[0] < 0)
            {
                return;
            }
            DynamicObjectCollection entityDataObject = View.Model.GetEntityDataObject(entryEntity);
            Dictionary<string, IGrouping<string, DynamicObject>> dictionary = (from g in entityDataObject
                                                                               group g by g.GetDynamicValue("PrdPPBomId", 0L) + "_" + g.GetDynamicValue<string>("ReplaceGroup")).ToDictionary((IGrouping<string, DynamicObject> d) => d.Key);
            List<DynamicObject> list = new List<DynamicObject>();
            int[] array = selectedRows;
            foreach (int num in array)
            {
                DynamicObject entityDataObject2 = View.Model.GetEntityDataObject(entryEntity, num);
                if (list.Contains(entityDataObject2))
                {
                    continue;
                }
                long value = View.Model.GetValue("FPrdPPBomId", num, 0L, "FEntity");
                decimal value2 = View.Model.GetValue("FReplaceGroup", num, 0m, "FEntity");
                string key = value + "_" + value2;
                dictionary.TryGetValue(key, out var value3);
                if (value3.IsEmpty())
                {
                    continue;
                }
                if (value3.Count() == 1)
                {
                    list.Add(entityDataObject2);
                    continue;
                }
                foreach (DynamicObject item in value3)
                {
                    list.Add(item);
                }
            }
            foreach (DynamicObject item2 in list)
            {
                View.Model.DeleteEntryRow("FEntity", entityDataObject.IndexOf(item2));
            }
            ReSetSeq();
        }

        private void ReSetSeq()
        {
            EntryEntity entryEntity = View.BusinessInfo.GetEntryEntity("FEntity");
            DynamicObjectCollection entityDataObject = View.Model.GetEntityDataObject(entryEntity);
            IEnumerable<DynamicObject> enumerable = entityDataObject.OrderBy((DynamicObject o) => o.GetDynamicValue("PrdPPBomId", 0L)).ThenBy((DynamicObject t) => t.GetDynamicValue("ReplaceGroup", 0m)).ThenBy((DynamicObject n) => n.GetDynamicValue<string>("MaterialType"));
            int num = 1;
            foreach (DynamicObject item in enumerable)
            {
                item.SetDynamicObjectItemValue("Seq", num);
                num++;
            }
        }

        private void SetComReplaceMustQty(int rowIndex, DynamicObjectCollection entryDatas, decimal useRate)
        {
            string groupId = View.Model.GetValue("FGroup", rowIndex, "", "FEntity");
            if (groupId.IsNullOrEmptyOrWhiteSpace())
            {
                return;
            }
            List<DynamicObject> list = entryDatas.Where((DynamicObject w) => w.GetDynamicValue<string>("Group") == groupId && w.GetDynamicValue("IsLock", defValue: false)).ToList();
            if (list.IsEmpty())
            {
                return;
            }
            foreach (DynamicObject item in list)
            {
                int row = entryDatas.IndexOf(item);
                View.Model.SetValue("FUseRate", useRate, row);
            }
        }

        protected void UseRateChanged(int row)
        {
            if (!View.Model.GetValue("FIsLock", row, defValue: true, "FEntity"))
            {
                return;
            }
            long value = View.Model.GetValue("FPPBOMID", row, 0L, "FEntity");
            dicppbomDatas.TryGetValue(value, out var value2);
            if (!value2.IsNullOrEmpty())
            {
                long ppbomEntryId = View.Model.GetValue("FPPBOMEntryId", row, 0L, "FEntity");
                DynamicObjectCollection dynamicValue = value2.FirstOrDefault().GetDynamicValue<DynamicObjectCollection>("PPBomEntry");
                DynamicObject dynamicObject = dynamicValue.Where((DynamicObject w) => w.GetDynamicValue("Id", 0L) == ppbomEntryId).FirstOrDefault();
                int row2 = dynamicValue.IndexOf(dynamicObject);
                decimal value3 = View.Model.GetValue("FUseRate", row, 0m, "FEntity");
                dynamicObject.SetDynamicObjectItemValue("UseRate", value3);
                decimal num = PPBOMCalQtyServiceHelper.CalStdQty(base.Context, value2.FirstOrDefault(), row2);
                View.Model.SetValue("FStdQty", num, row);
                dynamicObject.SetDynamicObjectItemValue("StdQty", num);
                decimal num2 = PPBOMCalQtyServiceHelper.CalNeedQty(base.Context, value2.FirstOrDefault(), row2);
                View.Model.SetValue("FNeedQty", num2, row);
                dynamicObject.SetDynamicObjectItemValue("NeedQty", num2);
                View.Model.SetValue("FMustQty", PPBOMCalQtyServiceHelper.CalMustQty(base.Context, value2.FirstOrDefault(), row2), row);
                decimal num3 = PPBOMCalQtyServiceHelper.CalConsumeQty(base.Context, value2.FirstOrDefault(), row2);
                View.Model.SetValue("FConsumeQty", PPBOMCalQtyServiceHelper.CalConsumeQty(base.Context, value2.FirstOrDefault(), row2), row);
                dynamicObject.SetDynamicObjectItemValue("ConsumeQty", num3);
                View.Model.SetValue("FWipQty", PPBOMCalQtyServiceHelper.CalWipQty(base.Context, value2.FirstOrDefault(), row2), row);
            }
        }
    }
}
